import time
import json
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import tkinter as tk
from tkinter import ttk, scrolledtext
from threading import Thread
url = 'https://passport.jd.com/new/login.aspx?ReturnUrl=https%3A%2F%2Fwww.jd.com%2F'
class PDDCrawlerApp:
    def __init__(self, root):
        self.root = root
        self.root.title("京东Cookies保存工具")
        self.root.geometry("900x700")
        self.root.configure(bg="#f5f5f5")
        
        # 设置Chrome选项
        self.chrome_options = Options()
        self.chrome_options.add_argument("--disable-gpu")
        self.chrome_options.add_argument("--no-sandbox")
        self.chrome_options.add_argument("--disable-dev-shm-usage")
        self.chrome_options.add_argument("--disable-software-rasterizer")
        self.chrome_options.add_argument("--disable-webgl")
        self.chrome_options.add_argument("--disable-features=VizDisplayCompositor")
        
        self.driver = None
        self.cookie_file = "jd_cookies.json"
        self.setup_ui()
        
    def setup_ui(self):
        # 标题
        title_label = tk.Label(self.root, text="京东Cookies保存工具", font=("Arial", 18, "bold"), 
                              fg="#ff453a", bg="#f5f5f5")
        title_label.pack(pady=20)
        
        # 说明
        desc_label = tk.Label(self.root, text="此工具用于登录京东并保存Cookies", 
                             font=("Arial", 12), bg="#f5f5f5", fg="#666")
        desc_label.pack(pady=5)
        
        # URL输入框
        url_frame = tk.Frame(self.root, bg="#f5f5f5")
        url_frame.pack(pady=10, padx=20, fill="x")
        
        tk.Label(url_frame, text="京东登录URL:", font=("Arial", 10), bg="#f5f5f5").pack(anchor="w")
        
        self.url_var = tk.StringVar(value=url)
        url_entry = tk.Entry(url_frame, textvariable=self.url_var, font=("Arial", 10), width=70)
        url_entry.pack(pady=5, fill="x")
        
        # 按钮框架
        btn_frame = tk.Frame(self.root, bg="#f5f5f5")
        btn_frame.pack(pady=15)
        
        self.start_btn = tk.Button(btn_frame, text="开始登录", command=self.start_login, 
                                  bg="#ff453a", fg="white", font=("Arial", 12), width=15)
        self.start_btn.pack(side="left", padx=10)
        
        self.clear_btn = tk.Button(btn_frame, text="清除结果", command=self.clear_results, 
                                  bg="#666", fg="white", font=("Arial", 12), width=15)
        self.clear_btn.pack(side="left", padx=10)
        
        # 进度条
        self.progress = ttk.Progressbar(self.root, mode="indeterminate")
        self.progress.pack(pady=10, padx=20, fill="x")
        
        # 结果展示区域
        result_frame = tk.Frame(self.root, bg="#f5f5f5")
        result_frame.pack(pady=10, padx=20, fill="both", expand=True)
        
        tk.Label(result_frame, text="操作结果:", font=("Arial", 12, "bold"), bg="#f5f5f5").pack(anchor="w")
        
        self.result_text = scrolledtext.ScrolledText(result_frame, height=20, width=100, font=("Arial", 10))
        self.result_text.pack(pady=10, fill="both", expand=True)
        
        # 状态栏
        self.status_var = tk.StringVar(value="就绪")
        status_bar = tk.Label(self.root, textvariable=self.status_var, relief="sunken", anchor="w", 
                             font=("Arial", 10), bg="white", fg="#333")
        status_bar.pack(side="bottom", fill="x")
    
    def save_cookies(self, cookies):
        """将Cookies保存到文件"""
        with open(self.cookie_file, 'w', encoding='utf-8') as f:
            json.dump(cookies, f, ensure_ascii=False, indent=2)
    
    def start_login(self):
        # 禁用开始按钮，防止重复点击
        self.start_btn.config(state="disabled")
        self.progress.start(10)
        self.status_var.set("正在初始化浏览器...")
        
        # 在新线程中运行登录和保存Cookies
        thread = Thread(target=self.login_and_save_cookies)
        thread.daemon = True
        thread.start()
    
    def login_and_save_cookies(self):
        try:
            # 初始化浏览器
            self.driver = webdriver.Chrome(options=self.chrome_options)
            self.driver.get(self.url_var.get())
            
            self.status_var.set("请在15秒内完成扫码登录...")
            
            # 等待30秒以确保用户有时间登录
            time.sleep(25)
            
            # 检测是否登录成功（假设登录后跳转到personal.html）
            # try:
            #     WebDriverWait(self.driver, 10).until(
            #         EC.url_contains("personal.html")
            #     )
            self.status_var.set("登录成功，正在保存Cookies...")
            # except Exception as e:
            #     raise Exception("登录超时或未跳转到个人页面，请确保扫码登录成功")
            
            # 获取并保存Cookies
            cookies = self.driver.get_cookies()
            self.save_cookies(cookies)
            cookie_str = "\n".join([f"{cookie['name']}: {cookie['value']}" for cookie in cookies])
            self.root.after(0, self.update_results, [f"已保存Cookies到 {self.cookie_file}:\n{cookie_str}\n{'-'*50}\n"])
            
        except Exception as e:
            error_msg = f"登录或保存Cookies过程中出错: {str(e)}"
            self.root.after(0, self.show_error, error_msg)
        
        finally:
            if self.driver:
                self.driver.quit()
            
            self.root.after(0, self.operation_finished)
    
    def update_results(self, results):
        self.result_text.delete(1.0, tk.END)
        for result in results:
            self.result_text.insert(tk.END, result)
        
        self.status_var.set("Cookies保存完成")
    
    def show_error(self, error_msg):
        self.result_text.delete(1.0, tk.END)
        self.result_text.insert(tk.END, error_msg)
        self.status_var.set("操作失败")
    
    def operation_finished(self):
        self.progress.stop()
        self.start_btn.config(state="normal")
    
    def clear_results(self):
        self.result_text.delete(1.0, tk.END)
        self.status_var.set("已清除结果")
    
    def __del__(self):
        if self.driver:
            self.driver.quit()

if __name__ == "__main__":
    root = tk.Tk()
    app = PDDCrawlerApp(root)
    root.mainloop()